import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { OrganizeTreeNode } from "@/types";
import { organizeService } from "@/api";
import { success } from "@/utils/toast";

export const useOrganizeStore = defineStore("organize", () => {
  // 状态
  const organizeTree = ref<OrganizeTreeNode[]>([]);
  const selectedOrganize = ref<OrganizeTreeNode | null>(null);
  const currentOrganize = ref<OrganizeTreeNode | null>(null);
  const loading = ref(false);
  const searchKeyword = ref("");

  // 计算属性
  const hasSelectedOrganize = computed(() => !!selectedOrganize.value);
  const isTopLevel = computed(() => selectedOrganize.value?.parentId === 0);

  /**
   * 获取组织架构树
   */
  const fetchOrganizeTree = async () => {
    try {
      loading.value = true;
      const response = await organizeService.getOrganizeTree();
      // 将扁平数据转换为树形结构
      organizeTree.value = buildOrganizeTree(response.data);
    } catch (error) {
      console.error("获取组织架构失败:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 构建组织架构树
   */
  const buildOrganizeTree = (flatData: any[]): OrganizeTreeNode[] => {
    if (!Array.isArray(flatData)) return [];

    // 创建节点映射
    const nodeMap = new Map<number, OrganizeTreeNode>();
    const rootNodes: OrganizeTreeNode[] = [];

    // 初始化所有节点
    flatData.forEach((item) => {
      const node: OrganizeTreeNode = {
        id: item.id,
        name: item.name,
        abbreviation: item.abbreviation,
        code: item.code,
        parentId: item.parentId,
        children: [],
      };
      nodeMap.set(item.id, node);
    });

    // 构建树形结构
    flatData.forEach((item) => {
      const node = nodeMap.get(item.id)!;

      if (item.parentId === 0) {
        // 根节点
        rootNodes.push(node);
      } else {
        // 子节点
        const parent = nodeMap.get(item.parentId);
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(node);
        }
      }
    });

    return rootNodes;
  };

  /**
   * 创建组织
   */
  const createOrganize = async (organizeData: any) => {
    try {
      loading.value = true;
      const response = await organizeService.createOrganize(organizeData);
      if (response.success || response.code === 200) {
        success("组织创建成功");
        await fetchOrganizeTree();
        return response.data;
      }
    } catch (error) {
      console.error("创建组织失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新组织
   */
  const updateOrganize = async (organizeData: any) => {
    try {
      loading.value = true;
      const response = await organizeService.updateOrganize(organizeData);
      if (response.success || response.code === 200) {
        success("组织更新成功");
        await fetchOrganizeTree();
        return response.data;
      }
    } catch (error) {
      console.error("更新组织失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 删除组织
   */
  const deleteOrganize = async (id: number) => {
    try {
      loading.value = true;
      const response = await organizeService.deleteOrganize(id);
      if (response.success || response.code === 200) {
        success("组织删除成功");
        await fetchOrganizeTree();
        // 如果删除的是当前选中的组织，清空选中状态
        if (selectedOrganize.value?.id === id) {
          selectedOrganize.value = null;
        }
      }
    } catch (error) {
      console.error("删除组织失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 移动组织
   */
  const moveOrganize = async (id: number, newParentId: number) => {
    try {
      loading.value = true;
      const response = await organizeService.moveOrganize(id, newParentId);
      if (response.success || response.code === 200) {
        success("组织移动成功");
        await fetchOrganizeTree();
      }
    } catch (error) {
      console.error("移动组织失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 搜索组织
   */
  const searchOrganizes = async (keyword: string) => {
    try {
      loading.value = true;
      const response = await organizeService.searchOrganizes(keyword);
      if (response.success || response.code === 200) {
        // 这里可以根据需要处理搜索结果
        return response.data;
      }
    } catch (error) {
      console.error("搜索组织失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 验证组织编码
   */
  const validateCode = async (code: string, excludeId?: number) => {
    try {
      const response = await organizeService.validateCode(code, excludeId);
      if (response.success || response.code === 200) {
        return response.data.valid;
      }
      return false;
    } catch (error) {
      console.error("验证编码失败:", error);
      return false;
    }
  };

  /**
   * 获取组织路径
   */
  const getOrganizePath = async (id: number) => {
    try {
      const response = await organizeService.getOrganizePath(id);
      if (response.success || response.code === 200) {
        return response.data;
      }
      return [];
    } catch (error) {
      console.error("获取组织路径失败:", error);
      return [];
    }
  };

  /**
   * 根据ID查找组织节点
   */
  const findOrganizeById = (
    id: number,
    nodes = organizeTree.value
  ): OrganizeTreeNode | null => {
    for (const node of nodes) {
      if (node.id === id) {
        return node;
      }
      if (node.children) {
        const found = findOrganizeById(id, node.children);
        if (found) return found;
      }
    }
    return null;
  };

  /**
   * 设置选中的组织
   */
  const setSelectedOrganize = (organize: OrganizeTreeNode | null) => {
    selectedOrganize.value = organize;
  };

  /**
   * 设置当前编辑的组织
   */
  const setCurrentOrganize = (organize: OrganizeTreeNode | null) => {
    currentOrganize.value = organize;
  };

  /**
   * 设置搜索关键词
   */
  const setSearchKeyword = (keyword: string) => {
    searchKeyword.value = keyword;
  };

  /**
   * 重置状态
   */
  const resetState = () => {
    organizeTree.value = [];
    selectedOrganize.value = null;
    currentOrganize.value = null;
    searchKeyword.value = "";
  };

  return {
    // 状态
    organizeTree,
    selectedOrganize,
    currentOrganize,
    loading,
    searchKeyword,

    // 计算属性
    hasSelectedOrganize,
    isTopLevel,

    // 方法
    fetchOrganizeTree,
    createOrganize,
    updateOrganize,
    deleteOrganize,
    moveOrganize,
    searchOrganizes,
    validateCode,
    getOrganizePath,
    findOrganizeById,
    setSelectedOrganize,
    setCurrentOrganize,
    setSearchKeyword,
    resetState,
  };
});
